<?php
/**
 * 自定义页面管理
 */
namespace Admin\Controller;
use Think\Controller;

class PageController extends Controller{

    /**
     * 列表页
     */
    public function index(){
        $this->display();
    }

    /**
     * 数据接口
     */
    public function getdata(){
        C('api_table',true);
        $p = I('page') ? I('page') : 1;
        $row = I('limit') ? I('limit') : 10;
        $query = '';
        if($_GET['searchtype'] && $_GET['keywords']){
            $query = $_GET['searchtype'].' like "%'.$_GET['keywords'].'%"';
        }
        $m = M('Page');
        $data['page']['total'] = $m->where($query)->count();
        //处理删除最后一条数据的时候没有数据的bug,请求最后一页没有数据的bug
        if(floor(($data['page']['total'] + $row - 1) / $row) < $p){
            $p = $p - 1;
        }
        $data['data'] = $m->where($query)->page($p,$row)->select();
        //$data['sql'] = $m->_sql();
        $data['page']['cur'] = $p;
        $data['page']['row'] = $row;

        _apiReturn(1, L('success'), $data, $url); //数据获取成功
    }

    /**
     * 页面编辑页
     */
    public function edit(){
        if(I("id")){
            $this->info = M("Page")->find(I("id"));
        }
        $this->display();
    }

    /**
     * 数据提交接口
     */
    public function edit_post(){
        if(IS_POST){
            $m = M("Page");
            if(I('post.id')){
                $data = I('post.');
                $data['update_time'] = Date('Y-m-d H:i:s');
                $res = $m->data($data)->save();
            }else{
                $data = I('post.');
                $data['uid'] = (int)$_SESSION['loginUser']['id'];
                $data['create_time'] = Date('Y-m-d H:i:s');
                $res = $m->data($data)->add();
            }
            if($res){
                _apiReturn(1,'success');
            }else{
                _apiReturn(0,'error');
            }
        }
    }

    /**
     * 数据删除接口
     */
    public function del(){
        D('Page')->_del(I("ids"));
    }
    public function editpage(){
        $data = M("Page")->where("id=".I('get.id'))->getField('config');
        $data = json_decode($data,true);
        $this->info = $data;
        $this->display();
    }
    public function editpage_post(){
        if(IS_POST){
            $m = M("Page");
            if(I('post.id')){
                $pagedata = I('post.');
                unset($pagedata['id']);
                unset($pagedata['__hash__']);
                $data['id'] = I('post.id');
                $data['uid'] = (int)$_SESSION['loginUser']['id'];
                $data['update_time'] = Date('Y-m-d H:i:s');
                $data['config'] = json_encode($pagedata,JSON_UNESCAPED_UNICODE);
                $res = $m->data($data)->save();
            }
            if($res){
                _apiReturn(1,'success');
            }else{
                _apiReturn(0,'error');
            }
        }
    }

}